package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis缓存数据初始化监听器
 *
 * mongodb --- > redis
 * 1>攻略统计对象vo
 * 2>用户攻略收藏列表[拓展]
 *
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent>{
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    //当spring容器启动并初始化之后马上执行该方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("-------------攻略vo对象初始化-start----------------------------");
        //1: 查询mongodb所有攻略
        List<Strategy> list = strategyService.list();

        //2:遍历所有攻略,封装成vo对象
        for (Strategy strategy : list) {
            //存在问题: 如果第一次初始化后, 前端进行vo对象统计, redis中统计数据跟数据库中数据不一致了
            //          如果第二次再进行初始化, 后面操作会覆盖之前redis缓存的vo对象.
            //解决方案: 如果vo已经存在了, 直接跳过, 不需要初始化
            if(strategyStatisVORedisService.isStrategyVoExist(strategy.getId())){
                continue;
            }

            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());

            strategyStatisVORedisService.setStrategyStatisVo(vo);
        }
        //3:将vo缓存到redis中

        System.out.println("-------------攻略vo对象初始化-end------------------------------");
    }
}
